<template>
  <div class="club-activities-container">
    <!-- 活动列表 -->
    <h2 class="section-title">活动管理</h2>
    <div class="action-bar">
      <el-button type="primary" @click="addActivity">
        <i class="el-icon-plus"></i> 新建活动
      </el-button>
    </div>
    <div v-if="sortedActivities && sortedActivities.length > 0">
      <el-table
        :data="sortedActivities"
        style="width: 100%"
        stripe
        :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
        :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
        v-loading="loading"
      >
        <!-- <el-table-column label="海报" width="120">
          <template #default="scope">
            <div class="activity-poster" @click="showPoster(scope.row.poster)">
              <el-image 
                :src="getImageUrl(scope.row.poster)" 
                fit="cover"
                style="width: 80px; height: 45px; border-radius: 4px; cursor: pointer;"
              >
                <template #error>
                  <div class="no-poster">无海报</div>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="status" label="状态" min-width="90">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activename" label="活动名称" min-width="150"></el-table-column>
        <el-table-column label="开始时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(new Date(scope.row.activetime)) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(new Date(scope.row.endTime)) }}
          </template>
        </el-table-column>
        <el-table-column prop="activeadd" label="活动地点" min-width="150"></el-table-column>
        <el-table-column label="报名人数" min-width="100">
          <template #default="scope">
            {{ getParticipantCount(scope.row) }} / {{ scope.row.maxParticipants || '不限' }}
          </template>
        </el-table-column>
        <el-table-column label="活动描述" min-width="200">
          <template #default="scope">
            {{ scope.row.description }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="370" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewActivity(scope.row)"
            >查看</el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="viewApplications(scope.row)"
            >报名管理</el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="editActivity(scope.row)"
              :disabled="scope.row.status === 'completed'"
            >编辑</el-button>
            <el-button 
              v-if="scope.row.status === 'upcoming'"
              size="small" 
              type="info" 
              @click="startActivity(scope.row)"
            >开始活动</el-button>
            <el-button 
              v-if="scope.row.status === 'ongoing'"
              size="small" 
              type="danger" 
              @click="endActivity(scope.row)"
            >结束活动</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="confirmDelete(scope.row)"
              :disabled="scope.row.status === 'ongoing'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else class="no-data-message">
      暂无活动数据
      <div v-if="activities.length > 0" class="no-data-hint">
        (已获取到{{activities.length}}条数据，但排序后为空，请查看控制台日志)
      </div>
    </div>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog
      :title="isEdit ? '编辑活动' : '新建活动'"
      v-model="showAddDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="activityForm" :rules="activityRules" ref="activityFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="activename">
          <el-input v-model="activityForm.activename"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="activetime">
          <el-date-picker
            v-model="activityForm.activetime"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY/MM/DD HH:mm"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY/MM/DD HH:mm"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="活动地点" prop="activeadd">
          <el-input v-model="activityForm.activeadd"></el-input>
        </el-form-item>
        <el-form-item label="人数上限" prop="maxParticipants">
          <el-input-number 
            v-model="activityForm.maxParticipants" 
            :min="1" 
            :max="500"
            :step="5"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" v-model="activityForm.description" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitActivity">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看活动报名对话框 -->
    <el-dialog
      title="活动报名管理"
      v-model="showApplicationsDialog"
      width="70%"
    >
      <div v-if="selectedActivity">
        <div class="activity-info">
          <h3>{{ selectedActivity.activename }}</h3>
          <p><i class="el-icon-time"></i> {{ formatDateTime(new Date(selectedActivity.activetime)) }}</p>
          <p><i class="el-icon-location"></i> {{ selectedActivity.activeadd }}</p>
          <p><i class="el-icon-user"></i> 已报名人数：{{ getParticipantCount(selectedActivity) }} / {{ selectedActivity.maxParticipants || '不限' }}</p>
        </div>
        <el-divider></el-divider>

        <el-table
          :data="getAllParticipants()"
          style="width: 100%"
          stripe
          :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
          :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
          v-loading="participantsLoading"
        >
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <img
                :src="scope.row.avatar || '../../components/icons/touxiang.png'"
                alt="用户头像"
                style="width: 40px; height: 40px; border-radius: 50%;"
              >
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
          <el-table-column prop="contact" label="联系方式" width="150"></el-table-column>
          <el-table-column prop="registerTime" label="报名时间" width="180">
            <template #default="scope">
              {{ formatDateTime(new Date(scope.row.registerTime)) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                @click="removeParticipant(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showApplicationsDialog = false">关闭</el-button>
          <el-button @click="exportParticipantsList" type="primary">导出报名列表</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="showDeleteDialog"
      width="30%"
    >
      <p>确定要删除活动 "{{ activityToDelete?.activename }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteActivity">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看活动详情对话框 -->
    <el-dialog
      title="活动详情"
      v-model="showActivityDetailDialog"
      width="70%"
    >
      <div v-if="selectedActivity" class="activity-detail">
        <div class="detail-header">
          <h2>{{ selectedActivity.activename }}</h2>
          <el-tag :type="getStatusTagType(selectedActivity.status)">
            {{ getStatusText(selectedActivity.status) }}
          </el-tag>
            </div>

        <div class="detail-info">
          <el-descriptions :column="2">
            <el-descriptions-item label="开始时间">{{ formatDateTime(new Date(selectedActivity.activetime)) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(new Date(selectedActivity.endTime)) }}</el-descriptions-item>
            <el-descriptions-item label="活动地点">{{ selectedActivity.activeadd }}</el-descriptions-item>
            <el-descriptions-item label="人数上限">{{ selectedActivity.maxParticipants || '不限' }}</el-descriptions-item>
            <el-descriptions-item label="已报名人数">{{ getParticipantCount(selectedActivity) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ selectedActivity.createdAt ? formatDateTime(new Date(selectedActivity.createdAt)) : '未知' }}</el-descriptions-item>
          </el-descriptions>
      </div>

        <div class="detail-desc" v-if="selectedActivity.description">
          <h3>活动描述</h3>
          <div class="desc-content">{{ selectedActivity.description }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showActivityDetailDialog = false">关闭</el-button>
          <el-button
            type="success"
            @click="viewApplications(selectedActivity)"
          >报名管理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps, defineComponent, reactive, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getClubId, formatDateTime } from '@/utils/common'

// 活动表格组件
const ActivityTable = defineComponent({
  props: {
    activities: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['view', 'edit', 'delete', 'view-applications', 'start', 'end', 'view-poster'],
  setup(props, { emit }) {
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case 'upcoming': return 'info'
        case 'ongoing': return 'warning'
        case 'completed': return 'success'
        default: return 'info'
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'upcoming': return '即将开始'
        case 'ongoing': return '正在进行'
        case 'completed': return '已结束'
        default: return '未知'
      }
    }

    // 获取报名人数
    const getParticipantCount = (activity) => {
      const approvedCount = activity.participants?.filter(p => p.status === 'approved').length || 0;
      return approvedCount;
    }

    // 处理图片URL路径
    const getImageUrl = (posterPath) => {
      if (!posterPath) return '/components/icons/default-activity.png';
      
      // 如果已经是完整路径，直接返回
      if (posterPath.startsWith('http') || posterPath.startsWith('blob:')) {
        return posterPath;
      }
      
      // 如果是相对路径，加上服务器地址
      if (posterPath.startsWith('/uploads/') || posterPath.startsWith('uploads/')) {
        return `http://localhost:5000${posterPath.startsWith('/') ? '' : '/'}${posterPath}`;
      }
      
      // 否则认为是文件名，补全路径
      return `http://localhost:5000/uploads/${posterPath}`;
    };

    return {
      getStatusTagType,
      getStatusText,
      getParticipantCount,
      getImageUrl
    }
  },
  template: `
    <el-table
      :data="activities"
      style="width: 100%"
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
    >
      <el-table-column label="海报" width="120">
        <template #default="scope">
          <div class="activity-poster" @click="$emit('view-poster', scope.row.poster)">
            <el-image 
              :src="getImageUrl(scope.row.poster)" 
              fit="cover"
              style="width: 80px; height: 45px; border-radius: 4px; cursor: pointer;"
            >
              <template #error>
                <div class="no-poster">无海报</div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="activename" label="活动名称" width="180"></el-table-column>
      <el-table-column label="开始时间" width="160">
        <template #default="scope">
          {{ formatDateTime(new Date(scope.row.activetime)) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" width="160">
        <template #default="scope">
          {{ formatDateTime(new Date(scope.row.endTime)) }}
        </template>
      </el-table-column>
      <el-table-column prop="activeadd" label="活动地点" width="150"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报名人数" width="120">
        <template #default="scope">
          {{ getParticipantCount(scope.row) }} / {{ scope.row.maxParticipants || '不限' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320">
        <template #default="scope">
          <el-button 
            size="small" 
            type="primary" 
            @click="$emit('view', scope.row)"
          >查看</el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="$emit('view-applications', scope.row)"
          >报名管理</el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="$emit('edit', scope.row)"
            :disabled="scope.row.status === 'completed'"
          >编辑</el-button>
          <el-button 
            v-if="scope.row.status === 'upcoming'"
            size="small" 
            type="info" 
            @click="$emit('start', scope.row)"
          >开始活动</el-button>
          <el-button 
            v-if="scope.row.status === 'ongoing'"
            size="small" 
            type="danger" 
            @click="$emit('end', scope.row)"
          >结束活动</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="$emit('delete', scope.row)"
            :disabled="scope.row.status === 'ongoing'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  `
})

// 辅助函数 - 处理图片URL路径
const getImageUrl = (posterPath) => {
  if (!posterPath) return '../../components/icons/default-activity.png';
  
  // 如果已经是完整路径，直接返回
  if (posterPath.startsWith('http') || posterPath.startsWith('blob:')) {
    return posterPath;
  }
  
  // 如果是相对路径，加上服务器地址
  if (posterPath.startsWith('/uploads/') || posterPath.startsWith('uploads/')) {
    return `http://localhost:5000${posterPath.startsWith('/') ? '' : '/'}${posterPath}`;
  }
  
  // 否则认为是文件名，补全路径
  return `http://localhost:5000/uploads/${posterPath}`;
};

// 报名表格组件
const ApplicationTable = defineComponent({
  props: {
    applications: {
      type: Array,
      default: () => []
    },
    showActions: {
      type: Boolean,
      default: true
    }
  },
  emits: ['approve', 'reject'],
  template: `
    <el-table
      :data="applications"
      style="width: 100%"
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
    >
      <el-table-column label="头像" width="80">
        <template #default="scope">
          <img 
            :src="scope.row.user.avatar || '../../components/icons/touxiang.png'" 
            alt="用户头像" 
            style="width: 40px; height: 40px; border-radius: 50%;"
          >
        </template>
      </el-table-column>
      <el-table-column prop="user.name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="registerTime" label="报名时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200" v-if="showActions">
        <template #default="scope">
          <el-button 
            size="small" 
            type="success" 
            @click="$emit('approve', scope.row)"
          >通过</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="$emit('reject', scope.row)"
          >拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
  `
})

// 接收社团ID属性
const props = defineProps({
  clubId: {
    type: [String, Number],
    required: true
  }
})

// 注册组件
const components = {
  ActivityTable,
  ApplicationTable
}

// 显式添加调试日志
console.log('注册的组件:', components);
console.log('ActivityTable组件:', ActivityTable);

// 状态变量
const loading = ref(false)
const activities = ref([])
const activeTab = ref('upcoming')
const applicationTab = ref('pending')
const showAddDialog = ref(false)
const showApplicationsDialog = ref(false)
const showDeleteDialog = ref(false)
const showActivityDetailDialog = ref(false)
const isEdit = ref(false)
const selectedActivity = ref(null)
const activityToDelete = ref(null)

// 活动表单
const activityFormRef = ref(null)
const activityForm = ref({
  id: '',
  activename: '',
  activetime: '',
  endTime: '',
  activeadd: '',
  description: '',
  maxParticipants: 50,
  poster: '',
  posterFile: null,
  status: 'upcoming'
})

// 表单验证规则
const activityRules = {
  activename: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  activetime: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  activeadd: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请设置人数上限', trigger: 'blur', type: 'number' }
  ]
}

// 辅助函数 - 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'upcoming': return 'info'
    case 'ongoing': return 'warning'
    case 'completed': return 'success'
    default: return 'info'
  }
}

// 辅助函数 - 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'upcoming': return '即将开始'
    case 'ongoing': return '正在进行'
    case 'completed': return '已结束'
    default: return '未知'
  }
}

// 辅助函数 - 获取报名人数
const getParticipantCount = (activity) => {
  if (!activity || !activity.participants) {
    return 0;
  }
  const approvedCount = activity.participants.filter(p => p.status === 'approved').length || 0;
  return approvedCount;
}

// 根据状态获取活动
const getActivitiesByStatus = (status) => {
  console.log('获取活动状态:', status);
  console.log('获取活动状态:', activities.value.status);
  return activities.value.filter(activity => activity.status === status)
}

// 按创建时间排序的活动
const sortedActivities = computed(() => {
  console.log('排序前的活动列表:', activities.value);
  
  // 防止空数组或非数组导致的错误
  if (!activities.value || !Array.isArray(activities.value) || activities.value.length === 0) {
    console.log('活动列表为空或无效');
    return [];
  }
  
  try {
    const sorted = [...activities.value].sort((a, b) => {
      // 检查是否有有效对象
      if (!a || !b) {
        console.log('排序时遇到无效对象:', a, b);
        return 0;
      }
      
      // 首先尝试使用createdAt字段排序
      let dateA, dateB;
      
      try {
        dateA = a.createdAt ? new Date(a.createdAt) : null;
        dateB = b.createdAt ? new Date(b.createdAt) : null;
      } catch (err) {
        console.warn('日期解析错误:', err);
        dateA = null;
        dateB = null;
      }
      
      // 如果两个日期都有效，按createdAt比较
      if (dateA && dateB && !isNaN(dateA.getTime()) && !isNaN(dateB.getTime())) {
        console.log(`使用createdAt排序: ${a.activename} vs ${b.activename}`);
        return dateB.getTime() - dateA.getTime(); // 降序排列，新的在前面
      }
      
      // 如果createdAt不可用，尝试使用活动时间排序
      let actTimeA, actTimeB;
      
      try {
        actTimeA = a.activetime ? new Date(a.activetime) : null;
        actTimeB = b.activetime ? new Date(b.activetime) : null;
      } catch (err) {
        console.warn('活动时间解析错误:', err);
        actTimeA = null;
        actTimeB = null;
      }
      
      if (actTimeA && actTimeB && !isNaN(actTimeA.getTime()) && !isNaN(actTimeB.getTime())) {
        console.log(`使用activetime排序: ${a.activename} vs ${b.activename}`);
        return actTimeA.getTime() - actTimeB.getTime(); // 按活动时间升序排列，近期的在前面
      }
      
      // 如果日期都无效，则按名称排序
      console.log(`使用名称排序: ${a.activename} vs ${b.activename}`);
      return a.activename?.localeCompare(b.activename || '') || 0;
    });
    
    console.log('排序后的活动列表:', sorted);
    return sorted;
  } catch (error) {
    console.error('排序活动列表时发生错误:', error);
    return [...activities.value]; // 失败时返回原始列表
  }
});

// 根据状态获取活动报名
const getApplicationsByStatus = (status) => {
  if (!selectedActivity.value) return []
  return selectedActivity.value.participants.filter(app => app.status === status)
}

// 获取所有参与者，不考虑状态
const getAllParticipants = () => {
  if (!selectedActivity.value || !selectedActivity.value.participants) return [];
  return selectedActivity.value.participants;
}

// 导出参与者列表
const exportParticipantsList = () => {
  if (!selectedActivity.value || !selectedActivity.value.participants || selectedActivity.value.participants.length === 0) {
    ElMessage.warning('没有报名数据可导出');
    return;
  }

  try {
    // 准备CSV数据
    const headers = ['用户名', '真实姓名', '学号', '联系方式', '报名时间', '备注'];
    const participants = selectedActivity.value.participants;

    let csvContent = headers.join(',') + '\n';

    participants.forEach(p => {
      const row = [
        p.username || '',
        p.realName || '',
        p.studentId || '',
        p.contact || '',
        p.registerTime ? formatDateTime(new Date(p.registerTime)) : '',
        (p.remark || '').replace(/,/g, ' ') // 替换备注中的逗号以避免CSV格式问题
      ];
      csvContent += row.join(',') + '\n';
    });

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${selectedActivity.value.activename}_报名名单.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('报名名单导出成功');
  } catch (error) {
    console.error('导出报名名单失败:', error);
    ElMessage.error('导出报名名单失败');
  }
}

// 删除参与者
const participantsLoading = ref(false);

const removeParticipant = async (participant) => {
  try {
    if (!selectedActivity.value || !participant) {
      ElMessage.error('无法删除报名信息：缺少必要参数');
        return;
      }
      
    // 确认删除
    await ElMessageBox.confirm(
      `确定要删除用户 "${participant.realName || participant.username}" 的报名信息吗？此操作不可撤销。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    participantsLoading.value = true;

    // 删除报名信息
    const activityId = selectedActivity.value._id;
    const userId = participant.userId;

    if (!activityId || !userId) {
      throw new Error('缺少活动ID或用户ID');
    }

    // 调用API删除报名记录
    await axios.delete(`http://localhost:5000/clubs/${props.clubId}/activities/${activityId}/participants/${userId}`);

    // 更新本地数据
    if (selectedActivity.value.participants) {
      selectedActivity.value.participants = selectedActivity.value.participants.filter(p => p.userId !== userId);
    }

    // 重新加载活动列表以更新报名人数
    await loadActivities();

    ElMessage.success('报名信息已删除');
  } catch (error) {
    if (error === 'cancel') return;

    console.error('删除报名信息失败:', error);
    ElMessage.error(error.response?.data?.message || '删除报名信息失败');
  } finally {
    participantsLoading.value = false;
  }
}

// 查看活动
const viewActivity = (activity) => {
  console.log('查看活动详情:', activity);
  selectedActivity.value = activity;
  showActivityDetailDialog.value = true;
}

// 编辑活动
const editActivity = (activity) => {
  console.log('开始编辑活动:', activity);
  
  // 检查活动ID
  let activityId = activity._id;
  if (!activityId && activity.id) {
    activityId = activity.id;
    console.log('使用备选ID字段 "id":', activityId);
  }
  
  if (!activityId) {
    console.error('错误: 活动缺少ID，无法编辑');
    ElMessage.error('无法编辑活动: 缺少活动ID');
    return;
  }
  
  isEdit.value = true;
  
  // 复制活动数据到表单
  activityForm.value = {
    id: activityId,
    activename: activity.activename,
    activetime: activity.activetime,
    endTime: activity.endTime,
    activeadd: activity.activeadd,
    description: activity.description,
    maxParticipants: activity.maxParticipants || 50,
    poster: activity.poster,
    posterFile: null,
    status: activity.status
  };
  
  console.log('活动表单已填充:', activityForm.value);
  showAddDialog.value = true;
}

// 创建或更新活动
const submitActivity = async () => {
  if (!activityFormRef.value) return
  
  await activityFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        // 检查必填字段
        if (!activityForm.value.activename || !activityForm.value.activetime || !activityForm.value.activeadd) {
          ElMessage.error('请填写所有必填字段');
          loading.value = false;
          return;
        }
        
        console.log('准备提交活动表单数据:', activityForm.value);
        
        // 判断是否有文件要上传
        const hasFileToUpload = activityForm.value.posterFile !== null;
        console.log('是否有文件需要上传:', hasFileToUpload);

        // 根据是否有文件选择不同的提交方式
        if (hasFileToUpload) {
          // 如果有文件，使用FormData提交
          const formData = new FormData();

          // 添加基本字段
          formData.append('activename', activityForm.value.activename);
          formData.append('activetime', activityForm.value.activetime instanceof Date
            ? activityForm.value.activetime.toISOString()
            : activityForm.value.activetime);
          formData.append('endTime', activityForm.value.endTime instanceof Date
            ? activityForm.value.endTime.toISOString()
            : activityForm.value.endTime);
          formData.append('activeadd', activityForm.value.activeadd);
          formData.append('description', activityForm.value.description || '');
          formData.append('maxParticipants', parseInt(activityForm.value.maxParticipants));
          formData.append('status', activityForm.value.status || 'upcoming');

          // 添加文件
          formData.append('file', activityForm.value.posterFile);

          let response;
          if (isEdit.value) {
            // 更新活动
            const activityId = activityForm.value.id;
            console.log('使用FormData更新活动:', activityId);
            response = await axios.put(
              `http://localhost:5000/clubs/${props.clubId}/activities/${activityId}`,
              formData,
              { headers: { 'Content-Type': 'multipart/form-data' } }
            );
          } else {
            // 创建活动
            console.log('使用FormData创建活动');
            response = await axios.post(
              `http://localhost:5000/clubs/${props.clubId}/activities`,
              formData,
              { headers: { 'Content-Type': 'multipart/form-data' } }
            );
          }

          console.log('活动保存响应:', response.data);
          ElMessage.success(isEdit.value ? '活动更新成功' : '活动创建成功');
        } else {
          // 如果没有文件，使用普通JSON提交
          // 准备活动数据JSON对象
        const activityData = {
          activename: activityForm.value.activename,
          activetime: activityForm.value.activetime instanceof Date 
            ? activityForm.value.activetime.toISOString() 
            : activityForm.value.activetime,
          endTime: activityForm.value.endTime instanceof Date 
            ? activityForm.value.endTime.toISOString() 
            : activityForm.value.endTime,
          activeadd: activityForm.value.activeadd,
          description: activityForm.value.description || '',
          maxParticipants: parseInt(activityForm.value.maxParticipants),
            status: activityForm.value.status || 'upcoming',
            poster: activityForm.value.poster // 保留已有的海报URL
        };
        
        let response;
        if (isEdit.value) {
            // 更新活动
            const activityId = activityForm.value.id;
            console.log('更新活动:', activityId);
          response = await axios.put(
            `http://localhost:5000/clubs/${props.clubId}/activities/${activityId}`, 
            activityData
          );
        } else {
            // 创建活动
            console.log('创建活动');
          response = await axios.post(
            `http://localhost:5000/clubs/${props.clubId}/activities`, 
            activityData
          );
          }

          console.log('活动保存响应:', response.data);
          ElMessage.success(isEdit.value ? '活动更新成功' : '活动创建成功');
        }
        
        showAddDialog.value = false;
        resetForm();
        await loadActivities(); // 重新加载活动列表
      } catch (error) {
        console.error('提交活动失败', error);
        if (error.response) {
          console.error('错误详情:', error.response.data);
        }
        ElMessage.error(error.response?.data?.message || '提交活动失败');
      } finally {
        loading.value = false;
      }
    }
  });
}

// 重置表单
const resetForm = () => {
  activityForm.value = {
    id: '',
    activename: '',
    activetime: '',
    endTime: '',
    activeadd: '',
    description: '',
    maxParticipants: 50,
    poster: '',
    posterFile: null,
    status: 'upcoming'
  }
  isEdit.value = false
}

// 确认删除
const confirmDelete = (activity) => {
  activityToDelete.value = activity
  showDeleteDialog.value = true
}

// 删除活动
const deleteActivity = async () => {
  try {
    loading.value = true
    await axios.delete(`http://localhost:5000/clubs/${props.clubId}/activities/${activityToDelete.value._id}`);
    ElMessage.success('活动删除成功');
    showDeleteDialog.value = false;
    activityToDelete.value = null;
    await loadActivities(); // 重新加载活动列表
  } catch (error) {
    console.error('删除活动失败', error);
    ElMessage.error(error.response?.data?.message || '删除活动失败');
  } finally {
    loading.value = false;
  }
}

// 查看活动报名
const viewApplications = (activity) => {
  selectedActivity.value = activity
  applicationTab.value = 'pending'
  showApplicationsDialog.value = true
}

// 开始活动
const startActivity = async (activity) => {
  try {
    loading.value = true;
    // 调用API更新活动状态
    const response = await axios.put(`http://localhost:5000/clubs/${props.clubId}/activities/${activity._id}`, {
      status: 'ongoing'
    });
    
    if (response.status === 200) {
      // 更新本地活动状态
      const index = activities.value.findIndex(a => a._id === activity._id);
      if (index !== -1) {
        activities.value[index].status = 'ongoing';
      }
      
      ElMessage.success(`活动"${activity.activename}"已开始`);
    }
  } catch (error) {
    console.error('更新活动状态失败', error);
    ElMessage.error(`更新活动状态失败: ${error.response?.data?.message || error.message}`);
  } finally {
    loading.value = false;
  }
}

// 结束活动
const endActivity = async (activity) => {
  try {
    loading.value = true;
    // 调用API更新活动状态
    const response = await axios.put(`http://localhost:5000/clubs/${props.clubId}/activities/${activity._id}`, {
      status: 'completed'
    });
    
    if (response.status === 200) {
      // 更新本地活动状态
      const index = activities.value.findIndex(a => a._id === activity._id);
      if (index !== -1) {
        activities.value[index].status = 'completed';
      }
      
      ElMessage.success(`活动"${activity.activename}"已结束`);
    }
  } catch (error) {
    console.error('更新活动状态失败', error);
    ElMessage.error(`更新活动状态失败: ${error.response?.data?.message || error.message}`);
  } finally {
    loading.value = false;
  }
}

// 对话框控制
const showActivities = ref(false)
const showActivityForm = ref(false)
const showApprovalDialog = ref(false)
const showPosterPreview = ref(false) // 控制海报预览弹窗
const previewPoster = ref(null) // 当前预览的海报URL

// 加载活动数据
const loadActivities = async () => {
  loading.value = true
  try {
    console.log('开始加载社团活动列表, 社团ID:', props.clubId);

    if (!props.clubId) {
      console.error('错误: 社团ID为空，无法加载活动');
      ElMessage.error('无法加载活动: 社团ID为空');
      loading.value = false;
    return;
  }
  
    // 从API获取社团活动数据
    console.log(`正在从API获取数据: http://localhost:5000/clubs/${props.clubId}/activities`);
    const response = await axios.get(`http://localhost:5000/clubs/${props.clubId}/activities`);

    console.log('API响应:', response);
    console.log('响应状态:', response.status);
    console.log('响应数据类型:', typeof response.data);

    if (response.data) {
      console.log('活动列表加载成功, 收到', response.data.length, '个活动');
      console.log('原始活动数据:', JSON.stringify(response.data).substring(0, 500) + '...');

      // 验证返回的数据是否为数组
      if (!Array.isArray(response.data)) {
        console.error('错误: API返回的数据不是数组:', response.data);
        activities.value = [];
        loading.value = false;
        return;
      }

      // 处理返回的活动列表
      activities.value = response.data.map((activity, index) => {
        console.log(`处理活动 ${index + 1}:`, activity);

        // 检查活动对象是否有效
        if (!activity || typeof activity !== 'object') {
          console.error(`错误: 活动 ${index + 1} 无效:`, activity);
          return null;
        }

        // 检查活动ID
        if (!activity._id) {
          console.warn(`警告: 活动 ${index + 1} 缺少_id字段:`, activity);
          // 尝试寻找替代ID
          if (activity.id) {
            console.log(`使用替代ID (id) 作为 _id: ${activity.id}`);
            activity._id = activity.id;
          }
        }

        // 检查必要字段
        if (!activity.activename) {
          console.warn(`警告: 活动 ${index + 1} 缺少活动名称:`, activity);
          activity.activename = `未命名活动 ${index + 1}`;
        }

        // 处理海报URL
        if (activity.poster) {
          console.log(`原始海报URL: ${activity.poster}`);
          activity.poster = getImageUrl(activity.poster);
          console.log(`处理后的海报URL: ${activity.poster}`);
        }

        // 确保有createdAt字段用于排序
        if (!activity.createdAt) {
          // 如果没有createdAt字段，尝试使用活动创建的时间戳
          console.log(`活动 ${index + 1} 缺少createdAt字段，使用替代日期`);
          activity.createdAt = activity.activetime || new Date().toISOString();
          console.log(`设置的createdAt值: ${activity.createdAt}`);
        }

        // 修复日期显示，确保ISO格式日期字符串
        if (activity.activetime && typeof activity.activetime === 'string') {
          try {
            const date = new Date(activity.activetime);
            if (!isNaN(date.getTime())) {
              activity.displayTime = formatDateTime(date);
              console.log(`格式化后的活动时间: ${activity.displayTime}`);
            } else {
              console.warn(`警告: 活动时间 "${activity.activetime}" 无法解析为有效日期`);
            }
          } catch (e) {
            console.warn(`日期格式化错误 (${activity.activename}):`, e);
          }
        }

        // 确保participants字段存在
        if (!activity.participants) {
          console.warn(`警告: 活动 ${index + 1} 缺少participants字段，设置为空数组`);
          activity.participants = [];
        }

        // 检查并设置默认状态
        if (!activity.status) {
          console.warn(`警告: 活动 ${index + 1} 缺少status字段，设置为upcoming`);
          activity.status = 'upcoming';
        }

        console.log(`活动 ${index + 1} 处理完成:`, activity);
        return activity;
      }).filter(activity => activity !== null); // 过滤掉无效的活动

      console.log('活动列表处理完成，共有', activities.value.length, '个有效活动');
      console.log('处理后的活动数据:', activities.value);
    } else {
      console.log('没有活动数据或响应为空');
      activities.value = [];
    }
    loading.value = false
  } catch (error) {
    console.error('加载活动失败', error);
    if (error.response) {
      console.error('错误响应状态:', error.response.status);
      console.error('错误响应数据:', error.response.data);
    } else if (error.request) {
      console.error('未收到响应，请求详情:', error.request);
    } else {
      console.error('错误信息:', error.message);
    }
    ElMessage.error('加载活动失败: ' + (error.response?.data?.message || error.message));
    activities.value = [];
    loading.value = false;
  }
}

// 添加新活动
const addActivity = () => {
  isEdit.value = false;
  resetForm();
  showAddDialog.value = true;
}

onMounted(async () => {
  console.log('组件挂载，准备加载活动数据');
  await loadActivities();
  console.log('当前活动数据:', activities.value);
  console.log('排序后的活动数据:', sortedActivities.value);
});
</script>
<style>
body {
  background-color: #1f1b24;
  margin: 0;
  padding: 0;
}
</style>
<style scoped>
.club-activities-container {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #ffffff;
}

.section-title {
  margin: 0;
  font-size: 22px;
  color: #ffffff;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.upload-area {
  border: 2px dashed #424242;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3f51b5;
  background: rgba(63, 81, 181, 0.1);
}

.upload-placeholder {
  color: #b0bec5;
}

.upload-tip {
  color: #757575;
  font-size: 12px;
  margin-top: 8px;
}
.file-input {
  display: none;
}
.activity-tabs {
  margin-bottom: 20px;
}

.activity-info {
  margin-bottom: 20px;
}

.activity-info h3 {
  margin: 0 0 10px 0;
  color: #409EFF;
}

.activity-info p {
  margin: 5px 0;
  color: #b0bec5;
}

.application-tabs {
  margin-top: 20px;
}

/* 海报上传样式 */
.poster-uploader {
  display: block;
  margin-bottom: 10px;
  width: 100%;
}

.poster-upload-placeholder {
  width: 300px;
  height: 168px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #28232e;
}

.poster-upload-placeholder:hover {
  border-color: #409EFF;
}

.poster-upload-placeholder i {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.poster-preview {
  width: 300px;
  height: 168px;
  object-fit: cover;
  border-radius: 6px;
}

.poster-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.activity-poster {
  width: 80px;
  height: 45px;
  border-radius: 4px;
  overflow: hidden;
}

.no-poster {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #28232e;
  color: #8c939d;
  font-size: 12px;
}

.poster-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  background-color: #1a1a1a;
  border-radius: 8px;
}

.poster-full-preview {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 8px;
}

.no-poster-preview {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #28232e;
  color: #8c939d;
  font-size: 16px;
  border-radius: 8px;
}

.no-data-message {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #909399;
  background: #28232e;
  border-radius: 4px;
  margin-top: 20px;
}

.no-data-hint {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

/* 活动详情样式 */
.activity-detail {
  padding: 20px;
  background-color: #28232e;
  border-radius: 8px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h2 {
  margin: 0;
  color: #ffffff;
  font-size: 24px;
}

.detail-info {
  margin-bottom: 20px;
}

.detail-desc {
  margin-top: 20px;
  background-color: #1f1b24;
  padding: 15px;
  border-radius: 8px;
}

.detail-desc h3 {
  margin-top: 0;
  color: #409EFF;
  font-size: 18px;
  margin-bottom: 10px;
}

.desc-content {
  color: #b0bec5;
  white-space: pre-wrap;
  line-height: 1.6;
}
</style> 
